package com.bonc.apicreator.ctrl;


import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.bonc.apicreator.constant.BaseConstant;
import com.bonc.apicreator.dao.ApiDao;
import com.bonc.apicreator.dao.ModuleDao;
import com.bonc.apicreator.dao.ProjectDao;
import com.bonc.apicreator.entity.Module;
import com.bonc.apicreator.entity.Project;
import com.bonc.apicreator.entity.RestApi;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;


/**
 * api的controller
 *
 * @author gaopengyu
 * @version 2016年8月5日
 * @see ApiController
 * @since
 */
@Controller
@RequestMapping("/project/{proId}/api")
public class ApiController {
    /**
     * 日志对象
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(ApiController.class);

    /**
     * api的dao层
     */
    @Autowired
    private ApiDao apiDao;

    /**
     * project的dao层
     */
    @Autowired
    private ProjectDao projectDao;
    /**
     * module的dao层
     */
    @Autowired
    private ModuleDao moduleDao;


    /**
     * Description: 加载页面并获取tableName
     * 
     * @param proId
     * @return String
     * @see
     */
    @RequestMapping(value = "")
    public String list(Model model, @PathVariable Long proId) {
        model.addAttribute("proId", proId);
        List<String> list = new ArrayList<String>();
        Project project = projectDao.findOne(proId);
        List<Module> modules = moduleDao.findByProIdOrderBySort(proId);
        model.addAttribute("modules", modules);
        model.addAttribute("project", project);
        if (!project.isTextOnly()) {
            Connection conn = getConn(project);
            if (conn != null) {
                String sql = "show tables";
                PreparedStatement pstmt;
                try {
                    pstmt = (PreparedStatement)conn.prepareStatement(sql);
                    ResultSet rs = pstmt.executeQuery();
                    int col = rs.getMetaData().getColumnCount();
                    while (rs.next()) {
                        for (int i = 1; i <= col; i++ ) {
                            list.add(rs.getString(i));
                            if ((i == 2) && (rs.getString(i).length() < 8)) {

                            }
                        }
                    }
                    model.addAttribute("list", list);
                }
                catch (SQLException e) {
                    LOGGER.error("SQLException", e);
                }
            }
        }
        return "api/list.jsp";
    }

    /**
     * Description: ajax请求 API列表
     * 
     * @param pageable
     * @param condition
     * @param proId
     * @return Object
     * @see
     */
    @RequestMapping(value = {"/list"})
    @ResponseBody
    public Object getList(Pageable pageable, String condition, @PathVariable Long proId) {
        Map<String, Object> map = new HashMap<String, Object>();
        Page<RestApi> apiList;
        if (StringUtils.isEmpty(condition)) {
            apiList = apiDao.findByProIdOrderBySort(proId, pageable);
        }
        else {
            apiList = apiDao.findByProIdAndNameContainingOrderBySort(proId, condition, pageable);
        }
        map.put("list", apiList.getContent());
        map.put("count", apiList.getTotalElements());
        map.put("code", BaseConstant.STATE_SUCCESS);
        LOGGER.debug("list response:" + JSON.toJSONString(apiList));
        return map;
    }

    /**
     * Description: 新增api
     * 
     * @param api
     * @param proId
     * @return String
     * @see
     */
    @RequestMapping(value = {"/save"}, method = RequestMethod.POST)
    public String add(RestApi api,String moduleName, @PathVariable Long proId) {
        String url = api.getRequestUrl();
        if (!url.startsWith("/")) {
            url = "/" + url;
            api.setRequestUrl(url);
        }
        api.setModuleName(moduleName);
        if(null!=moduleName) {
            Module module  = moduleDao.findByNameAndProId(moduleName, proId);
            //System.out.println(module_+":"+module.getSort());
            api.setModuleSort(module.getSort());
            
        }
        api.setProId(proId);
        api.setCreateDate(new Date());
        apiDao.save(api);
        return "redirect:/project/{proId}/api";
    }

    /**
     * Description: 删除API
     * 
     * @param id
     * @param proId
     * @return String
     * @see
     */
    @RequestMapping(value = {"/delete"}, method = RequestMethod.POST)
    @ResponseBody
    public Object delete(Long id) {
        apiDao.delete(id);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("code", BaseConstant.STATE_SUCCESS);
        return map;
    }

    /**
     * Description: 重名校验
     * 
     * @param name
     * @param proId
     * @param id
     * @return Object
     * @see
     */
    @RequestMapping(value = {"/checkName"})
    @ResponseBody
    public Object checkName(String name, Long proId, String id) {
        RestApi api = null;
        if ("api_name".equals(id)) {
            api = apiDao.findByNameAndProId(name, proId);
        }
        if ("api_url".equals(id)) {
            api = apiDao.findByRequestUrlAndProId(name, proId);
        }
        Map<String, Object> map = new HashMap<String, Object>();
        if (!StringUtils.isEmpty(api)) {
            map.put("code", BaseConstant.STATE_CHONGFU);
            map.put("message", "已存在！");
        }
        return map;
    }

    /**
     * Description: 更新时先查询这条数据
     * 
     * @param model
     * @param id
     * @return Object
     * @see
     */
    @RequestMapping(value = {"/findOne"})
    @ResponseBody
    public Object findOne(Long id) {
        RestApi api = apiDao.findOne(id);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("code", BaseConstant.STATE_SUCCESS);
        map.put("message", "成功");
        map.put("api", api);
        return map;
    }

    /**
     * Description: 更新 目前更新描述和排序，后续根据需要放开
     * 
     * @param api
     * @param proId
     * @return String
     * @see
     */
    @RequestMapping(value = {"/update"}, method = RequestMethod.POST)
    public String update(RestApi api,String moduleName) {
        RestApi updateapi = apiDao.findOne(api.getId());
        api.setCreateDate(updateapi.getCreateDate());
        api.setModuleName(moduleName);
        if(null!=moduleName) {
        Module updateModule = moduleDao.findByNameAndProId(moduleName, api.getProId());
        api.setModuleSort(updateModule.getSort());
        }
        apiDao.save(api);
        return "redirect:/project/{proId}/api";
    }

    /**
     * Description: JDBC获取链接
     * 
     * @param project
     * @return Connection
     * @see
     */
    private static Connection getConn(Project project) {
        String driver = "com.mysql.jdbc.Driver";
        String url = project.getMysqlUrl();
        String username = project.getMysqlUsername();
        String password = project.getMysqlPassword();
        Connection conn = null;
        try {
            Class.forName(driver); // classLoader,加载对应驱动
            conn = (Connection)DriverManager.getConnection(url, username, password);
        }
        catch (ClassNotFoundException e) {
            LOGGER.error("ClassNotFoundException" + e.getMessage());
        }
        catch (SQLException e) {
            LOGGER.error("URL/UserName/Password ERROR" + e.getMessage());
        }
        return conn;
    }
}
